const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  // 商品名称
  name: {
    type: String,
    required: true,
    trim: true
  },
  // 商品描述
  description: {
    type: String,
    required: true
  },
  // 商品价格
  price: {
    type: Number,
    required: true
  },
  // 商品图片
  image: {
    type: String,
    required: true,
    default: 'default.jpg'
  },
  // 商品图片（轮播）
  images: {
    type: [String],
    default: []
  },
  // 关联到小分类
  subCategory: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'SubCategory',
    required: true
  },
  // 冗余存储大分类ID（优化查询性能）
  topCategory: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'TopCategory',
    required: true
  },
  // 商品标签(比如:衣服的尺码、手机的配置等等)
  Tabs:{
    type: [String],
    default: []
  },
  // 用户ID
  userId:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  // 库存
  stock: {
    type: Number,
    default: 100
  },
  // 销量
  sales: {
    type: Number,
    default: 0
  },
  // 是否上架
  isUp: {
    type: Boolean,
    default: false
  },
},
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
  });

// 虚拟字段：关联的小分类信息
productSchema.virtual('subCategoryInfo', {
 ref: 'SubCategory',
 localField: 'subCategory',
 foreignField: '_id',
 justOne: true
});

// 虚拟字段：关联的大分类信息
productSchema.virtual('topCategoryInfo', {
 ref: 'TopCategory',
 localField: 'topCategory',
 foreignField: '_id',
 justOne: true
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;